import {util} from '@/static/js/common.js';
import {login} from '@/static/js/global.js';

// 全局状态管理轮询
const messagePolling = {
    pollingTimer: null,
    isPolling: false,
    pollingInterval: 30000, // 30秒
    pollingCount: 0 // 轮询次数计数器
};

// 轮询未读消息
const getUnreadMessageCount = () => {
    // 如果已经有轮询在运行，则不再启动新的轮询
    if (messagePolling.isPolling) {
        
        return;
    }
    
    // 标记轮询开始
    messagePolling.isPolling = true;
    messagePolling.pollingCount++;

    
    util.get_request(
        {
            type: "getUnreadMessageCount",
        },
        (res) => {
            // 处理消息逻辑...
            if (res.count && res.count > 0) {
                util.funsetStorage("readMessageCount", res.count);
                uni.setTabBarBadge({
                    index: 4,
                    text: res.count > 99 ? '99+' : res.count.toString()
                });
                uni.showTabBarRedDot({
                    index: 4,
                    success: () => {},
                    fail: () => {}
                });
            } else {
                uni.removeStorageSync('readMessageCount');
                uni.hideTabBarRedDot({
                    index: 4,
                    success: () => {},
                    fail: () => {}
                });
            }
            
            // 成功处理后重置轮询状态
            messagePolling.isPolling = false;
            
            // 设置下一次轮询
            messagePolling.pollingTimer = setTimeout(() => {
                if (login.checkLogin() == true) {
                    getUnreadMessageCount();
                }
            }, messagePolling.pollingInterval);
        },
        () => {
            // 失败后重置轮询状态
            messagePolling.isPolling = false;
            
            // 设置下一次轮询
            messagePolling.pollingTimer = setTimeout(() => {
                if (login.checkLogin() == true) {
                    getUnreadMessageCount();
                }
            }, messagePolling.pollingInterval);
        },
        false
    );
};

// 停止消息轮询停止消息轮询
const stopMessagePolling = () => {
    if (messagePolling.pollingTimer) {
        clearTimeout(messagePolling.pollingTimer);
        messagePolling.pollingTimer = null;
    }
    messagePolling.isPolling = false;

};

// 启动消息轮询
const startMessagePolling = () => {
    // 如果已经有轮询在运行，先停止
    stopMessagePolling();
    getUnreadMessageCount();
};

// 获取未读数量
const getReadMessageCount = () => {
    return util.getStorageRoute('readMessageCount');
};

// 获取聊天列表
const getchatList = (call) => {
    util.get_request(
        {
            type: 'getchatList',
        },
        (res) => {
            if (call) {
                call(res);
            }
        },
        () => {},false
    );
};

// 删除指定消息
const deleteMessage = (msg_id,call) => {
    util.get_request(
        {
            type: 'deleteMessage',
			msg_id:msg_id,
        },
        (res) => {
            if (call) {
                call(res);
            }
        },
        () => {},false
    );
};

// 获取消息列表
const getUnreadList = (send_id,user_id='',call) => {
    util.get_request(
        {
            type: 'getUnreadList',
            user_id: user_id,
            send_id: send_id,
        },
        (res) => {
            if (call) {
                call(res);
            }
        },
        () => {},false
    );
};

// 发送图片信息
const sendImage = (user_id,imagePath,send_id,sender,send_avatar,bulkSendMode='',call) => {
	util.uploadFile(
		imagePath,
		{
			type:'sendImage',
			user_id:user_id,
            avatar: send_avatar,
            name: sender,
            id: send_id,
			bulkSendMode:bulkSendMode,
		},
		(res)=>{
            if (call) {
                call(res);
            }
		},
	)

};
// 发送信息
/* send_id,发送方id
sender,发送方名字
send_avatar, 发送方头像 */
const sendMessage = (user_id,content,send_id,sender,send_avatar,bulkSendMode='', call) => {
    util.get_request(
        {
            type: 'sendMessage',
            user_id: user_id,
            content: encodeURIComponent(content),
            avatar: send_avatar,
            name: sender,
            id: send_id,
			bulkSendMode:bulkSendMode,
        },
        (res) => {
            if (call) {
                call(res);
            }
        },
        () => {},false
    );
};
// 在应用启动时启动轮询
startMessagePolling();


// 导出方法
export const message = {
    getReadMessageCount,
    getchatList,
    startMessagePolling,
    stopMessagePolling,
	getUnreadList,
	sendMessage,
	sendImage,
	deleteMessage,
};